<template>
	<view class="page">
		<!-- 头部导航 -->
		<!-- <view class="header-bag">
			<image src="/static/icon-Get-into@3.png" class="back" @click="goBack"></image>
			<text class="font18 page-title">{{ pageTitle }}</text>
		</view> -->

		<!-- 主要内容 -->
		<view class="wrapper">
			<view class="identity font14">
				<view class="display-flex-l">
					<view class="display-flex-l">
						<text class="required">*</text>
						<text>合伙人资质（份）:</text>
					</view>
					<view class="display-flex-end rights">
						<view class="display-flex-end computer">
							<view class="subtract" @click="decreaseNum"></view>
							<input type="number" readonly class="num" v-model="quantity" />
							<view class="add" @click="increaseNum"></view>
						</view>
					</view>
				</view>
			</view>
			
			<view class="red-tip font10">
				合伙人资质1份<text>{{ price }}</text>元，最低1份起。
			</view>
			<view class="red-tip font10">
				优享优品平台将为您配置相对等额的保险保障
			</view>
			
			<view class="summarize font14">
				<view>合计支付金额:</view>
				<view>￥<text class="total">{{ totalAmount }}</text></view>
			</view>
			
			<view class="submit-btn font17" @click="showPayment">去支付</view>
		</view>

		<!-- 合伙人信息填写弹窗 -->
		<view v-if="showPartnerInfo" class="partner-info-modal">
			<!-- <view class="header-bag">
				<image src="/static/icon-Get-into@3.png" class="back" @click="hidePartnerInfo"></image>
				<view class="header-center">
					<text>填写合伙人信息</text>
				</view>
			</view> -->
			
			<view class="wrapper font15">
				<view class="info-box">
					<view class="layouts">
						<view class="label-with-required">
							<text class="must-write">*</text>
							<text>法人姓名:</text>
						</view>
						<view>
							<input v-model="partnerInfo.realname" readonly type="text" placeholder="请输入本人姓名" />
						</view>
					</view>
					
					<view class="layouts">
						<view class="label-with-required">
							<text class="must-write">*</text>
							<text>身份证号:</text>
						</view>
						<view>
							<input v-model="partnerInfo.idcardNum" type="number" readonly placeholder="请输入本人有效身份证号" />
						</view>
					</view>
				</view>
				
				<view class="id-card">
					<view :class="['checkbox', agreementChecked ? 'checked' : '']" @click="toggleAgreement"></view>
					<text class="agreement-text">
						我已阅读并同意<text class="agreement-link" @click="viewAgreement">《优享优品平台合伙人协议》</text>
					</text>
				</view>
				
				<view class="next-step" @click="nextStep">下一步</view>
			</view>
		</view>

		<!-- 支付方式选择弹窗 -->
		<view v-if="showPayMethod" class="pay-method-modal">
			<view class="mask" @click="hidePayMethod"></view>
			<view class="pay-content">
				<view class="close-btn" @click="hidePayMethod"></view>
				<view class="header font16">确认付款</view>
				<view class="show-amount font24">{{ showAmount }}</view>
				
				<view class="method balance-pay" @click="selectPayMethod('balance')">
					<text class="font17">账户余额</text>
					<text>{{ userBalance }}</text>
				</view>
				
				<view class="method wechat-pay" @click="selectPayMethod('wechat')">
					<text class="font17">微信支付</text>
					<image src="/static/icon-gengduo@2x.png"></image>
				</view>
				
				<view class="method bank-pay" @click="selectPayMethod('union')">
					<text class="font17">银联支付</text>
					<image src="/static/icon-gengduo@2x.png"></image>
				</view>
			</view>
		</view>

		<!-- 支付密码验证弹窗 -->
		<view v-if="showPasswordCheck" class="password-check-modal">
			<view class="header-bag">
				<image src="/static/icon-Get-into@3.png" class="back" @click="hidePasswordCheck"></image>
				<text class="font18 page-title">{{ passwordTitle }}</text>
			</view>
			
			<view class="wrapper">
				<view class="font13 pay-pw-head">请输入支付密码</view>
				<view class="input-div">
					<input 
						type="password" 
						v-model="payPassword" 
						maxlength="6" 
						@input="onPasswordInput"
						placeholder="请输入6位数字密码"
					/>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { partnerApi, paymentApi, userApi } from '@/api/index.js'
import { getToken, getCurrentUser } from '@/api/auth.js'
import { md5 } from '@/api/utils.js'

export default {
	data() {
		return {
			pageTitle: '购买合伙人资质',
			quantity: 1,
			price: 0,
			showPartnerInfo: false,
			showPayMethod: false,
			showPasswordCheck: false,
			agreementChecked: false,
			userBalance: '0.00',
			showAmount: '￥0.00',
			payPassword: '',
			passwordTitle: '检验支付密码',
			idType: 3, // 默认购买合伙人
			partnerInfo: {
				realname: '',
				idcardNum: ''
			},
			payType: '',
			isPasswordSet: false,
			firstPassword: '',
			secondPassword: ''
		}
	},
	
	computed: {
		totalAmount() {
			return (this.quantity * this.price).toFixed(2)
		}
	},
	
	onLoad(options) {
		this.initPage(options)
	},
	
	methods: {
		// 初始化页面
		async initPage(options) {
			// 根据参数设置页面标题和类型
			if (options.added == '1') {
				this.pageTitle = '追加合伙人资质'
			} else if (options.added == '0') {
				this.pageTitle = '购买合伙人资质'
				this.showPartnerInfo = true
			}
			uni.setNavigationBarTitle({ title: this.pageTitle })
			// 设置身份类型
			if (options.cityAgent == '0') {
				this.idType = 5 // 市代理
			} else if (options.cityAgent == '1') {
				this.idType = 4 // 代理人追加
			}
			
			if (options.added) {
				this.idType = 3
			}
			
			await this.getPartnerPrice()
			await this.getUserBalance()
			await this.getIdentityInfo()
		},
		
		// 获取合伙人价格
		async getPartnerPrice() {
			try {
				const res = await partnerApi.getPartnerMoney()
				if (res.r === 0) {
					this.price = res.data.price
				}
			} catch (error) {
				console.error('获取价格失败:', error)
			}
		},
		
		// 获取用户余额
		async getUserBalance() {
			try {
				const res = await paymentApi.getUserBalance()
				if (res.r === 0) {
					this.userBalance = res.data.withdraw_money
				}
			} catch (error) {
				console.error('获取余额失败:', error)
			}
		},
		
		// 获取身份信息
		async getIdentityInfo() {
			try {
				const res = await userApi.getIdentityInfo()
				if (res.r === 0) {
					this.partnerInfo.realname = res.data.realname
					this.partnerInfo.idcardNum = res.data.id_number
				}
			} catch (error) {
				console.error('获取身份信息失败:', error)
			}
		},
		
		// 增加数量
		increaseNum() {
			this.quantity++
		},
		
		// 减少数量
		decreaseNum() {
			if (this.quantity > 1) {
				this.quantity--
			} else {
				uni.showToast({
					title: '合伙人资质不能少于1份',
					icon: 'none'
				})
			}
		},
		
		// 显示支付方式
		async showPayment() {
			this.showAmount = `￥${this.totalAmount}`
			
			try {
				const res = await partnerApi.applyPay({
					type: this.idType,
					num: this.quantity
				})
				
				if (res.r === -4) {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				} else {
					this.showPayMethod = true
				}
			} catch (error) {
				console.error('创建订单失败:', error)
			}
		},
		
		// 隐藏支付方式
		hidePayMethod() {
			this.showPayMethod = false
		},
		
		// 选择支付方式
		selectPayMethod(type) {
			this.payType = type
			this.hidePayMethod()
			
			if (type === 'balance') {
				this.showPasswordVerification()
			} else if (type === 'wechat') {
				this.wechatPay()
			} else if (type === 'union') {
				this.unionPay()
			}
		},
		
		// 显示密码验证
		async showPasswordVerification() {
			try {
				const res = await paymentApi.checkPayPassword()
				if (res.data.is_set === 1) {
					this.passwordTitle = '请输入支付密码'
					this.isPasswordSet = true
				} else {
					this.passwordTitle = '设置支付密码'
					this.isPasswordSet = false
				}
				this.showPasswordCheck = true
			} catch (error) {
				console.error('检查支付密码失败:', error)
			}
		},
		
		// 隐藏密码验证
		hidePasswordCheck() {
			this.showPasswordCheck = false
			this.payPassword = ''
			this.firstPassword = ''
			this.secondPassword = ''
		},
		
		// 密码输入处理
		async onPasswordInput() {
			if (this.payPassword.length < 6) return
			
			if (!/^\d{6}$/.test(this.payPassword)) {
				uni.showToast({
					title: '支付密码由六位数字组成',
					icon: 'none'
				})
				this.payPassword = ''
				return
			}
			
			if (!this.isPasswordSet) {
				await this.handleSetPassword()
			} else {
				await this.handleVerifyPassword()
			}
		},
		
		// 处理设置密码
		async handleSetPassword() {
			if (!this.firstPassword) {
				this.firstPassword = this.payPassword
				this.payPassword = ''
				this.passwordTitle = '请再次输入支付密码'
			} else if (!this.secondPassword) {
				this.secondPassword = this.payPassword
				
				if (this.secondPassword !== this.firstPassword) {
					uni.showToast({
						title: '两次密码输入不一致',
						icon: 'none'
					})
					this.secondPassword = ''
					this.payPassword = ''
				} else {
					try {
						const res = await paymentApi.setPayPassword({
							pay_pwd: md5(this.firstPassword),
							pay_confirm_pwd: md5(this.secondPassword)
						})
						
						if (res.r === 0) {
							uni.showToast({
								title: '支付密码设置成功',
								icon: 'success'
							})
							this.isPasswordSet = true
							this.passwordTitle = '请输入支付密码'
							this.payPassword = ''
						}
					} catch (error) {
						console.error('设置支付密码失败:', error)
					}
				}
			}
		},
		
		// 处理验证密码
		async handleVerifyPassword() {
			try {
				const res = await paymentApi.verifyPayPassword({
					pay_pwd: md5(this.payPassword)
				})
				
				if (res.r !== 0) {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
					this.payPassword = ''
				} else {
					await this.processBalancePay()
				}
			} catch (error) {
				console.error('验证支付密码失败:', error)
				this.payPassword = ''
			}
		},
		
		// 处理余额支付
		async processBalancePay() {
			try {
				const orderRes = await partnerApi.applyPay({
					type: this.idType,
					num: this.quantity
				})
				
				if (orderRes.r !== 0) {
					uni.showToast({
						title: orderRes.msg,
						icon: 'none'
					})
					return
				}
				
				const payRes = await paymentApi.balancePay({
					order_num: orderRes.data.order_num,
					type: this.idType,
					num: this.quantity
				})
				
				if (payRes.r === 0) {
					this.hidePasswordCheck()
					uni.showToast({
						title: '支付成功',
						icon: 'success'
					})
					
					setTimeout(() => {
						this.navigateToSuccess()
					}, 1500)
				} else {
					uni.showToast({
						title: payRes.msg,
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('余额支付失败:', error)
			}
		},
		
		// 微信支付
		async wechatPay() {
			try {
				const orderRes = await partnerApi.applyPay({
					type: this.idType,
					num: this.quantity
				})
				
				if (orderRes.r !== 0) {
					uni.showToast({
						title: orderRes.msg,
						icon: 'none'
					})
					return
				}
				
				const openid = uni.getStorageSync('openid')
				const payRes = await paymentApi.wechatPay({
					order_num: orderRes.data.order_num,
					source: 5,
					type: this.idType,
					num: this.quantity,
					openid: openid
				})
				
				if (payRes.r === 0) {
					// 调用微信支付
					this.callWechatPay(payRes.data)
				} else {
					uni.showToast({
						title: payRes.msg,
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('微信支付失败:', error)
			}
		},
		
		// 调用微信支付
		callWechatPay(payData) {
			
			
			// 调用微信支付
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: String(payData.timeStamp),
				nonceStr: payData.nonceStr,
				package: payData.package,
				signType: payData.signType,
				paySign: payData.paySign,
				success: () => {
					uni.showToast({
						title: '支付成功',
						icon: 'success'
					})
					this.navigateToSuccess()
				},
				fail: (err) => {
					console.error('微信支付失败:', err)
					uni.showToast({
						title: '支付失败',
						icon: 'none'
					})
				}
			})
			
		},
		
		// 银联支付
		async unionPay() {
			try {
				const orderRes = await partnerApi.applyPay({
					type: this.idType,
					num: this.quantity
				})
				
				if (orderRes.r !== 0) {
					uni.showToast({
						title: orderRes.msg,
						icon: 'none'
					})
					return
				}
				
				const payRes = await paymentApi.unionPay({
					order_num: orderRes.data.order_num,
					source: 2,
					type: this.idType,
					num: this.quantity
				})
				
				if (payRes.r === 0) {
					// 处理银联支付跳转
					this.handleUnionPay(payRes.data.list.params)
				} else {
					uni.showToast({
						title: payRes.msg,
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('银联支付失败:', error)
			}
		},
		
		// 处理银联支付跳转
		handleUnionPay(params) {
			// 创建表单并提交到银联
			// 这里需要根据实际情况处理银联支付跳转
			console.log('银联支付参数:', params)
		},
		
		// 跳转到成功页面
		navigateToSuccess() {
			const params = {
				idtype: this.idType,
				payType: this.payType === 'balance' ? '余额支付' : this.payType === 'wechat' ? '微信支付' : '银联支付',
				totalp: this.showAmount
			}
			
			// 添加额外参数
			const options = this.$mp?.query || {}
			if (options.added) {
				params.added = options.added
			}
			if (options.from) {
				params.from = options.from
			}
			if (options.cityAgent) {
				params.cityAgent = options.cityAgent
			}
			
			const query = Object.keys(params).map(key => `${key}=${params[key]}`).join('&')
			uni.navigateTo({
				url: `/pages/identity/buyCooperative_succeed?${query}`
			})
		},
		
		// 隐藏合伙人信息弹窗
		hidePartnerInfo() {
			this.showPartnerInfo = false
		},
		
		// 切换协议勾选状态
		toggleAgreement() {
			this.agreementChecked = !this.agreementChecked
		},
		
		// 查看协议
		viewAgreement() {
			uni.setStorageSync('current_tag', 'hhr_xy')
			uni.navigateTo({
				url: '/pages/identity/agreement'
			})
		},
		
		// 下一步
		nextStep() {
			if (!this.agreementChecked) {
				uni.showToast({
					title: '请勾选 优享优品平台合伙人协议',
					icon: 'none'
				})
				return
			}
			this.hidePartnerInfo()
		},
		
		// 返回
		goBack() {
			uni.navigateBack()
		}
	}
}
</script>

<style lang="scss" scoped>
.page {
	background-color: #f5f5f5;
	min-height: 100vh;
}

.header-bag {
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
	height: 88rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #eee;
	
	.back {
		position: absolute;
		left: 30rpx;
		width: 40rpx;
		height: 40rpx;
	}
	
	.page-title {
		font-size: 36rpx;
		color: #333;
		font-weight: 500;
	}
	
	.header-center {
		text-align: center;
		font-size: 36rpx;
		color: #333;
	}
}

.wrapper {
	padding-top: 30rpx;
}

.identity {
	background-color: #fff;
	padding: 30rpx;
	border-radius: 20rpx;
	margin-bottom: 20rpx;
}

.display-flex-l {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.display-flex-end {
	display: flex;
	align-items: center;
}

.required {
	color: red;
	margin-right: 16rpx;
	font-size: 30rpx;
}

.computer {
	border: 1rpx solid #ddd;
	border-radius: 10rpx;
	overflow: hidden;
	
	.subtract, .add {
		width: 60rpx;
		height: 60rpx;
		background-color: #f8f8f8;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		
		&::before {
			content: '';
			width: 20rpx;
			height: 2rpx;
			background-color: #666;
		}
	}
	
	.add::after {
		content: '';
		position: absolute;
		width: 2rpx;
		height: 20rpx;
		background-color: #666;
	}
	
	.num {
		width: 100rpx;
		height: 60rpx;
		text-align: center;
		border: none;
		background-color: #fff;
		font-size: 28rpx;
	}
}

.red-tip {
	color: #ff6b6b;
	font-size: 24rpx;
	margin-bottom: 10rpx;
	margin-left: 40rpx;
	text {
		color: #ff6b6b;
		font-weight: bold;
	}
}

.summarize {
	display: flex;
	// justify-content: space-between;
	align-items: center;
	background-color: #fff;
	padding: 30rpx;
	border-radius: 20rpx;
	margin: 30rpx 0;
	font-size: 32rpx;
	
	.total {
		color: #ff6b6b;
		font-weight: bold;
		font-size: 36rpx;
	}
}

.submit-btn {
	background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
	color: #fff;
	text-align: center;
	padding: 30rpx;
	border-radius: 50rpx;
	font-size: 34rpx;
	font-weight: 500;
}

// 合伙人信息弹窗样式
.partner-info-modal {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: #f7f7f7;
	z-index: 1000;
	
	.info-box {
		background-color: #fff;
		padding-left: 40rpx;
		margin-bottom: 30rpx;
	}
	
	.layouts {
		display: flex;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #eee;
		
		&:last-child {
			border-bottom: none;
		}
		
		input {
			flex: 1;
			font-size: 30rpx;
			color: #333;
		}
	}
	
	.label-with-required {
		// position: relative;
		margin-right: 30rpx;
		display: flex;
		align-items: center;
		// min-width: 200rpx;
		
		.must-write {
			// position: absolute;
			// left: -20rpx;
			top: 5rpx;
			color: red;
			font-size: 30rpx;
		}
	}
	
	.id-card {
		display: flex;
		align-items: center;
		padding: 30rpx;
		
		.checkbox {
			width: 30rpx;
			height: 30rpx;
			border: 2rpx solid #ddd;
			border-radius: 6rpx;
			margin-right: 20rpx;
			position: relative;
			
			&.checked {
				background-color: #4CAF50;
				border-color: #4CAF50;
				
				&::after {
					content: '✓';
					position: absolute;
					color: #fff;
					font-size: 20rpx;
					left: 50%;
					top: 50%;
					transform: translate(-50%, -50%);
				}
			}
		}
		
		.agreement-text {
			font-size: 25rpx;
			color: #666;
		}
		
		.agreement-link {
			color: #4CAF50;
		}
	}
	
	.next-step {
		background-color: #ff2e00;
		color: #fff;
		text-align: center;
		padding: 30rpx;
		border-radius: 25rpx;
		font-size: 34rpx;
		margin: 30rpx;
	}
}

// 支付方式弹窗样式
.pay-method-modal {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	z-index: 1000;
	display: flex;
	align-items: flex-end;
	
	.mask {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
	}
	
	.pay-content {
		position: relative;
		width: 100%;
		max-height: 80vh;
		background-color: #fff;
		border-radius: 40rpx 40rpx 0 0;
		padding: 40rpx 30rpx;
		padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
		box-sizing: border-box;
		overflow-y: auto;
		
		.close-btn {
			position: absolute;
			top: 20rpx;
			right: 30rpx;
			width: 40rpx;
			height: 40rpx;
			cursor: pointer;
			
			&::before, &::after {
				content: '';
				position: absolute;
				width: 30rpx;
				height: 2rpx;
				background-color: #999;
				top: 50%;
				left: 50%;
				transform-origin: center;
			}
			
			&::before {
				transform: translate(-50%, -50%) rotate(45deg);
			}
			
			&::after {
				transform: translate(-50%, -50%) rotate(-45deg);
			}
		}
		
		.header {
			text-align: center;
			font-size: 32rpx;
			font-weight: 500;
			margin-bottom: 30rpx;
			padding-right: 70rpx;
		}
		
		.show-amount {
			text-align: center;
			font-size: 48rpx;
			font-weight: bold;
			color: #ff6b6b;
			margin-bottom: 40rpx;
		}
		
		.method {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 30rpx 0;
			border-bottom: 1rpx solid #eee;
			cursor: pointer;
			
			&:last-child {
				border-bottom: none;
			}
			
			&:active {
				background-color: #f5f5f5;
			}
			
			image {
				width: 40rpx;
				height: 40rpx;
			}
		}
	}
}

// 支付密码验证弹窗样式
.password-check-modal {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: #fff;
	z-index: 1000;
	
	.pay-pw-head {
		text-align: center;
		margin: 60rpx 0 40rpx;
		color: #666;
	}
	
	.input-div {
		padding: 0 60rpx;
		
		input {
			width: 100%;
			height: 80rpx;
			border: 2rpx solid #ddd;
			border-radius: 10rpx;
			text-align: center;
			font-size: 36rpx;
			letter-spacing: 10rpx;
		}
	}
}

.font10 { font-size: 20rpx; }
.font13 { font-size: 26rpx; }
.font14 { font-size: 28rpx; }
.font15 { font-size: 30rpx; }
.font16 { font-size: 32rpx; }
.font17 { font-size: 34rpx; }
.font18 { font-size: 36rpx; }
.font24 { font-size: 48rpx; }
</style>